<template>
  <section class="prizepool-manage">
    <div class="manage-title">新建/编辑奖品池</div>

    <section class="manage-main">
      <el-form ref="form" v-loading="formloading" :model="form" :rules="rules" label-width="150px" class="main-form">
        <el-form-item label="类型" prop="prizeType">
          <el-select v-model="form.prizeType" :disabled="state == 'update'" placeholder="请选择" style="width: 100%;" @change="lxChange">
            <el-option v-for="(item, index) in dict.BIGTPPT" :key="index" :label="item.dictName" :value="item.dictValue" />
            <!-- <el-option v-for="(item, index) in types" :key="index" :label="item.name" :value="item.value" /> -->
          </el-select>
        </el-form-item>
        <el-form-item label="奖品池名称" prop="prizeName">
          <el-input v-model="form.prizeName" placeholder="请输入奖品池名称" />
        </el-form-item>
        <el-form-item v-if="form.prizeType == '1'" label="充值记录" prop="rechargeId">
          <el-select v-model="form.rechargeId" :disabled="state == 'update'" placeholder="请选择" style="width:100%" @change="setMoney">
            <el-option v-for="(item, index) in rechList" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="奖品池说明" prop="prizeExplain">
          <el-input v-model="form.prizeExplain" type="textarea" placeholder="请输入奖品池说明" />
        </el-form-item>
        <el-form-item label="有效期时间段" required>
          <el-col :span="10">
            <el-form-item label prop="validTimeStart">
              <el-date-picker
                v-model="form.validTimeStart"
                type="datetime"
                :picker-options="pickeroptionsstart"
                placeholder="选择有效期开始日期"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="4">-</el-col>
          <el-col :span="10">
            <el-form-item label prop="validTimeEnd">
              <el-date-picker
                v-model="form.validTimeEnd"
                type="datetime"
                :picker-options="pickeroptionsend"
                placeholder="选择有效期截止日期"
                style="width: 100%;"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="总额" prop="prizeCount">
          <el-input-number v-model="form.prizeCount" :disabled="state == 'update' || form.prizeType == '1'" />
          <i class="el-icon-warning-outline" />如果是现金单位为"分"。
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">开启</el-radio>
            <el-radio label="0">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px;" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px;" type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </section>
</template>
<script>
import { getDictByCode, insert, update, get, getRech, getRechOne } from './../api'
export default {
  name: 'PrizepoolManage',
  data() {
    return {
      state: 'create',
      formloading: false,
      form: {
        id: '',
        prizeName: '',
        prizeType: '',
        prizeCount: 0,
        validTimeStart: '',
        validTimeEnd: '',
        prizeExplain: '',
        rechargeId: '',
        status: '1'
      },
      rules: {
        prizeName: [
          { required: true, message: '请输入奖品池名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        rechargeId: [{ required: true, message: '请选择充值记录', trigger: 'change' }],
        prizeType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        prizeCount: [{ required: true, message: '请输入总额', trigger: 'blur' }],
        prizeExplain: [{ required: true, message: '请输入奖品次说明', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        validTimeStart: [{ required: true, message: '请选择有效期开始日期', trigger: 'blur' }],
        validTimeEnd: [{ required: true, message: '请选择有效期截止日期', trigger: 'blur' }]
      },
      dict: {
        BIGTPPT: [] // 奖品类型
      },
      rechList: [], // 充值记录
      types: [
        {
          name: '积分',
          value: '0'
        },
        {
          name: '现金',
          value: '1'
        }
      ],
      pickeroptionsstart: {
        disabledDate: (time) => {
          if (this.form.validTimeEnd) {
            return time.getTime() > new Date(this.form.validTimeEnd).getTime()
          }
        }
      },
      pickeroptionsend: {
        disabledDate: (time) => {
          if (this.form.validTimeStart) {
            return time.getTime() < new Date(this.form.validTimeStart).getTime()
          }
        }
      }
    }
  },
  created() {
    this.state = this.$route.query.t === 'c' ? 'create' : 'update'
    for (const key in this.dict) {
      this.getDict(key)
    }
    if (this.$route.query.t === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    }
  },
  methods: {
    async lxChange(val) {
      this.form.rechargeId = ''
      this.form.prizeCount = 0
      if (val == 1) {
        this.rechList = await this.getRechList()
      }
    },
    setMoney(val) {
      let money = 0
      const obj = this.rechList.find((e) => {
        return e.id === val
      })
      money = obj ? obj.amount : 0
      this.form.prizeCount = parseFloat(money)
    },
    getRechList() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRech({ accountId: this.accId })
          .then((res) => {
            loading.close()
            const arr = res.data.data || []
            resolve(
              arr.map((a) => ({
                ...a,
                value: a.id,
                label: `${a.applyName}(${a.rechargeAmount}元)`
              }))
            )
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    getRechOneFun(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRechOne({ rechargeId: id })
          .then((res) => {
            loading.close()
            const arr = res.data.data || []
            resolve(
              arr.map((a) => ({
                ...a,
                value: a.id,
                label: `${a.applyName}(${a.rechargeAmount}元)`
              }))
            )
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    handleSubmit() {
      this.state === 'create' ? this.createData() : this.updateData()
    },

    handleCancel() {
      this.$router.push({ path: this.$filterPath('index') })
    },

    /*
     * 新增
     * */
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const { id, rechargeId, prizeName, prizeType, prizeCount, prizeExplain, validTimeStart, validTimeEnd, status } = this.form
          return new Promise((resolve, reject) => {
            insert({
              id,
              rechargeId,
              prizeName,
              prizeType,
              prizeCount,
              prizeExplain,
              validTimeStart,
              validTimeEnd,
              status
            })
              .then(() => {
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 1500
                })
                this.$router.push({ path: this.$filterPath('index') })
              })
              .catch((error) => {
                reject(error)
                loading.close()
              })
          })
        }
      })
    },

    /**
     * 编辑提交
     */
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const { id, rechargeId, prizeName, prizeType, prizeCount, prizeExplain, validTimeStart, validTimeEnd, status } = this.form
          return new Promise((resolve, reject) => {
            update({
              id,
              rechargeId,
              prizeName,
              prizeType,
              prizeCount,
              prizeExplain,
              validTimeStart,
              validTimeEnd,
              status
            })
              .then(() => {
                loading.close()
                this.dialogFormVisible = false
                this.$message({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.push({ path: this.$filterPath('index') })
              })
              .catch((error) => {
                reject(error)
                loading.close()
              })
          })
        }
      })
    },

    cancel() {
      this.$router.push({ path: this.$filterPath('index') })
    },

    /**
     * 获取详情
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get(id)
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              this.form[key] = data[key]
            }
            if (this.form.prizeType == '1') {
              this.getRechOneFun(this.form.rechargeId).then((res) => {
                this.rechList = res
              })
            }
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/mixin.scss';
.prizepool-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;
    .line {
      text-align: center;
    }
    .form-card {
      margin-top: 20px;
      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }
  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
